package ar.com.ctrln.view.dashboard.calendar;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventQueue;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import ar.com.ctrln.control.calendar.ConsultarTemaEvento;
import ar.com.ctrln.persistence.model.evento.TemaEvento;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class SeleccionarTemaEvento extends AbstractMinimizarVentana {

	private static final long serialVersionUID = -8364842460749427698L;

	@WireVariable
	ConsultarTemaEvento consultarTemaEvento;

	@Wire
	private Window wAgregarTemaEvento;

	@Wire
	private Listbox lbTemas;

	@Wire
	private Button btnSeleccionarTemasEventos;

	@Wire("#txtFilter")
	private Textbox txtFilter;

	@Wire
	private Label footer_label;

	private ListModelList<TemaEvento> modelo;

	private Set<TemaEvento> servicios;

	private Set<TemaEvento> seleccion = null;

	private Connection con;

	@SuppressWarnings("unchecked")
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		seleccion = (Set<TemaEvento>) this.getSelf().getParent()
				.getAttribute("temas");

		modelo = new ListModelList<TemaEvento>();

		modelo.setMultiple(true);

		lbTemas.setModel(modelo);

		modelo.addAll(consultarTemaEvento.listarEventos());

		lbTemas.setMultiple(true);

		lbTemas.setCheckmark(true);

		if (null != seleccion) {
			for (TemaEvento temaEvento : seleccion) {
				// por las dudas no lo agendo, no se si
				// sera nuevamente seleccionado
				temaEvento.setEstado(TemaEvento.SIN_AGENDAR);
			}
			modelo.setSelection(seleccion);
		}

	}

	@Listen("onClick = #btnSeleccionarTemasEventos")
	public void agregarServicios() {

		servicios = modelo.getSelection();

		EventQueue<Event> eq = EventQueues.lookup("seleccionarTemasEventos",
				EventQueues.DESKTOP, false);

		eq.publish(new Event("onButtonClick", btnSeleccionarTemasEventos,
				servicios));

		wAgregarTemaEvento.onClose();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Listen("onChanging = #txtFilter")
	public void getFilter(Event event) {
		((Textbox) event.getTarget())
				.setValue(((org.zkoss.zk.ui.event.InputEvent) event).getValue());

		ListModelList model = new ListModelList(getFilterBy(
				txtFilter.getValue(), modelo.getInnerList()));

		model.setMultiple(true);

		lbTemas.setModel(model);

		lbTemas.setModel(model);

		lbTemas.setMultiple(true);

		lbTemas.setCheckmark(true);

		if (lbTemas.getItemCount() > 0) {
			footer_label.setValue("");
			footer_label.setValue("Un total de " + lbTemas.getItemCount()
					+ " Tema/s");
		} else {
			footer_label.setValue("Ningun Resultado...");
			footer_label.setValue("");
		}
		((Textbox) event.getTarget()).setFocus(true);
	}

	public static List<TemaEvento> getFilterBy(String condicion,
			Collection<TemaEvento> contactos) {
		List<TemaEvento> data = new ArrayList<TemaEvento>();
		for (Iterator<TemaEvento> i = contactos.iterator(); i.hasNext();) {
			TemaEvento tmp = i.next();
			if (tmp.getNombre().toLowerCase()
					.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getEstado().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getObservacion().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0) {
				data.add(tmp);
			}
		}
		return data;
	}

	@Listen("onClick = #btnImprimir")
	public void imprimirTema() throws SQLException {

		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/ctrln", "root", "root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		String path = this.getPage().getDesktop().getWebApp()
				.getRealPath("/resources/reportes/.jrxml");
		String camino = path.replaceAll("\\\\", "/");

		try {
			Map param = new HashMap();
			param.put("", "");
			param.put("", "");
			param.put("", "");

			JasperReport jasperReport = JasperCompileManager
					.compileReport(camino);
			JasperPrint jasperPrint = JasperFillManager.fillReport(
					jasperReport, param, con);
			JasperViewer.viewReport(jasperPrint, false);
			con.close();
		} catch (JRException e) {
			e.printStackTrace();
		}

	}

}
